"""
综合助手智能体主程序
"""
import logging
from typing import AsyncGenerator

import uvicorn
from dotenv import load_dotenv

# 修复导入路径
import sys
import os

from contextlib import asynccontextmanager
from composite_agent.agent import CompositeAgent
from composite_agent.config import get_settings
from fastapi import FastAPI

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.server import A2AServer, api_router

# 加载环境变量
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

settings = get_settings()

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """应用生命周期管理"""

    # 启动时的初始化
    logger.info(f"🚀 启动 {settings.agent_name}")

    # TODO: 初始化数据库连接
    # TODO: 初始化Redis连接
    # TODO: 启动后台任务

    yield

    # 关闭时的清理
    logger.info("🛑 正在关闭应用...")

    # TODO: 清理数据库连接
    # TODO: 清理Redis连接
    # TODO: 停止后台任务

    logger.info("✅ 应用已关闭")

@api_router.get("/test")
async def test():
    """路由样例"""
    return {"message": f"test接口调用成功"}

def main():
    """主函数"""
    try:
        # 获取配置
        logger.info(f"启动综合助手智能体: {settings.agent_name}")
        logger.info(f"服务地址: http://{settings.server_host}:{settings.port}")

        # 创建智能体
        agent = CompositeAgent(settings)

        # 创建服务器
        server = A2AServer(
            agent_card=agent.agent_card,
            task_manager=agent.task_manager,
            host=settings.server_host,
            port=settings.port,
            lifespan=lifespan
        )

        app = server.get_app()
        # 启动服务器
        uvicorn.run(
            app,
            host=settings.server_host,
            port=settings.port,
            log_level=settings.log_level.lower()
        )

    except Exception as e:
        logger.error(f"启动综合智能体时发生错误: {e}")
        raise